package icu.shaoyayu.common.utll.encryption;

import icu.shaoyayu.common.utll.exception.CustomException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;

/**
 * @author shaoyayu
 * @date 2021/12/22
 * @apiNote
 */
public class HmacEncryption {

    private static final String KEY_MAC = "HmacMD5";

    /**
     * 随机生成key
     * @return
     */
    public static byte[] generateMacKey(){
        try {
            KeyGenerator kGen =  KeyGenerator.getInstance(KEY_MAC);
            SecretKey key = kGen.generateKey();
            //得到生成的key的编码
            return key.getEncoded();
        }catch (NoSuchAlgorithmException e){
            throw new CustomException("HKEN generateException:"+e.getMessage());
        }
    }

    /**
     * 加密后返回
     * @param originalText
     * @param secretKey
     * @return
     */
    public static byte[] encryption(String originalText,byte[] secretKey){
        try {
            SecretKey key = new SecretKeySpec(secretKey, KEY_MAC);
            Mac mac = Mac.getInstance(KEY_MAC);
            //把钥匙(salt 盐)传进去初始化
            mac.init(key);
            //调用update读入信息的字节码
            mac.update(originalText.getBytes(StandardCharsets.UTF_8));
            //得到加了钥匙后的算法加密后的信息的字节码：
            return mac.doFinal();
        }catch (Exception e){
            e.printStackTrace();
            throw new CustomException("encryption exception:"+e.getMessage());
        }
    }


}
